﻿using System;
using Newtonsoft.Json.Linq;
using ZYing.LiquidThemeEngine.Json;
using ZYing.LiquidThemeEngine.Config.Schemas.Settings;
using System.Collections.Concurrent;

namespace ZYing.LiquidThemeEngine.Config.Schemas.Json;

public class ThemeSettingItemSchemaJsonConverter : JsonCreationConverter<ThemeSettingItemSchema>
{
    private static ConcurrentDictionary<string, Func<ThemeSettingItemSchema>> _factories = new ConcurrentDictionary<string, Func<ThemeSettingItemSchema>>();
    public static void Register(string type, Func<ThemeSettingItemSchema> factory)
    {
        if (string.IsNullOrWhiteSpace(type)) throw new ArgumentNullException(nameof(type));
        if (factory == null) throw new ArgumentNullException(nameof(factory));
        _factories[type] = factory;
    }
    protected override ThemeSettingItemSchema Create(Type objectType, JObject jObject)
    {
        var type = jObject.Value<string>("type");
        switch (type)
        {
            case "checkbox":
                return new Checkbox();
            case "number":
                return new Number();
            case "radio":
                return new Radio();
            case "rang":
                return new Rang();
            case "select":
                return new Select();
            case "text":
                return new Text();
            case "textarea":
                return new Textarea();
            case "color":
                return new Color();
            case "html":
                return new Html();
            case "richtext":
                return new Richtext();
            case "url":
                return new Url();
            case "header":
                return new Header();
            case "paragraph":
                return new Paragraph();
        }
        if (_factories.TryGetValue(type, out var factory))
        {
            return factory();
        }

        return new UnKnow(jObject, type);
    }
}